/**
 * Created by SCR on 2017/8/9.
 */
var path = require('path');
var formidable = require('formidable');
var unzip = require('unzip');
var ObjectId = require('mongodb').ObjectID;
var fs = require('fs');
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var xmlparse = require('xml2js').parseString;

var FileOpera = require('../../utils/fileOpera');
var VisualModel = require('../../model/Integrate/visualization');
var CommonMethod = require('../../utils/commonMethod');
var setting = require('../../setting');

module.exports = (function () {

    // 根据文件夹名往数据库中添加条目，在从别处拷贝过来时这么用
    var __deployPackage = function (unzipPath, cb) {
        var _id = path.basename(unzipPath);
        VisualModel.getByOID(_id,function (err, rst) {
            if(err){
                return cb(err);
            }
            else{
                if(rst != null){
                    return cb(null);
                }

                var newPackage = {
                    // TODO id !
                    _id: _id,
                    schemas: [],
                    time: (new Date()).getTime()
                };
                var cfgPath = path.join(unzipPath, 'DataVisualizationMethod.xml');
                fs.readFile(cfgPath,'utf8',function (err, cfgStr) {
                    if(err){
                        return cb(err);
                    }
                    var doc = new dom().parseFromString(cfgStr);
                    // var rootNode = xpath.select('/DataVisualizationMethod',doc)[0];
                    // newPackage.guid = xpath.select('string(//@id)', rootNode);
                    // newPackage.wkname = xpath.select('string(//@wkname)', rootNode);
                    // newPackage.version = xpath.select('string(//@version)', rootNode);
                    //
                    //
                    // var zhLocalization = xpath.select('//Localization[@local=\'ZH_CN\']', rootNode)[0];
                    // var zhName = xpath.select('string(//@localName)', zhLocalization);
                    // var zhAbstract = xpath.select('string(//Abstract)', zhLocalization);
                    //
                    // var enLocalization = xpath.select('//Localization[@local=\'EN_US\']', rootNode)[0];
                    // var enName = xpath.select('string(//@localName)', enLocalization);
                    // var enAbstract = xpath.select('string(//Abstract)', enLocalization);
                    xmlparse(cfgStr, {
                        explicitArray: false,
                        ignoreAttrs: false
                    }, function (err, json) {
                        if(err) {
                            console.log('Error in parse DataVisualizationMethod.xml : ' + err);
                            return cb(err);
                        }
                        var jsonStr = JSON.stringify(json);
                        jsonStr = jsonStr.replace(/\"\$\"/g,'"_$"');
                        newPackage.DVM = JSON.parse(jsonStr).DataVisualizationMethod;

                        // save schema
                        var schemaNodes = xpath.select('/DataVisualizationMethod/Params//Param/@schema',doc);
                        for(let i=0;i<schemaNodes.length;i++){
                            var schemaPath = path.join(unzipPath,schemaNodes[i].nodeValue);
                            var schemaStr = fs.readFileSync(schemaPath,'utf8');
                            newPackage.schemas.push({
                                fname: schemaNodes[i].nodeValue,
                                value: schemaStr
                            });
                        }

                        VisualModel.save(newPackage,function (err, rst) {
                            if(err){
                                return cb(err);
                            }
                            return cb(null,rst._doc._id);
                        });
                    });
                });
            }
        });
    };

    return {
        // 只返回部分字段
        getPackageList: function (cb) {
            VisualModel.getByWhere({},function (err, visualList) {
                if(err){
                    return cb(err);
                }
                else{
                    var briefList = [];
                    for(let i=0;i<visualList.length;i++){
                        var abstract = '';
                        var zhAbstract = '';
                        var Localization = visualList[i].DVM.Localizations.Localization;
                        if(Localization instanceof Array){
                            for(let j=0;j<Localization.length;j++){
                                if(Localization[j]._$.local == 'EN_US'){
                                    abstract = Localization[j].Abstract;
                                    break;
                                }
                                else{
                                    zhAbstract = Localization[j].Abstract;
                                }
                            }
                            if(Localization.length != 0 && abstract == ''){
                                abstract = zhAbstract;
                            }
                        }
                        else{
                            abstract = Localization.Abstract;
                        }
                        briefList.push({
                            _id: visualList[i]._id,
                            wkname: visualList[i].DVM._$.wkname,
                            version: visualList[i].DVM._$.version,
                            enAbstract: abstract,
                            time: CommonMethod.timestamp2String(visualList[i].time)
                        });
                    }

                    return cb(null,briefList);
                }
            })
        },

        getPackageDetail: function (_id, cb) {
            VisualModel.getByOID(_id,function (err, visualService) {
                if(err){
                    return cb(err);
                }
                else{
                    return cb(null,visualService);
                }
            })
        },

        // TODO 待完成
        uploadPackage: function (fields, files, cb) {
            var _id = new ObjectId();
            var newPackage = {
                _id: _id,
                time: (new Date()).getTime()
            };
            var packagePath = files.package.path;
            var unzipPath = path.join(setting.visualpath, _id.toString());
            CommonMethod.Uncompress(packagePath, unzipPath,function (err) {
                if(err){
                    return cb(err);
                }
                var cfgPath = path.join(unzipPath, 'DataVisualizationMethod.xml');
                fs.readFile(cfgPath,'utf8',function (err, cfgStr) {
                    if(err){
                        return cb(err);
                    }
                    cfgStr = cfgStr.toString();
                    // var doc = new dom().parseFromString(cfgStr);
                    // var rootNode = xpath.select('/DataVisualizationMethod',doc)[0];
                    // newPackage.guid = xpath.select('string(//@id)', rootNode);
                    // newPackage.wkname = xpath.select('string(//@wkname)', rootNode);
                    // newPackage.version = xpath.select('string(//@version)', rootNode);
                    //
                    //
                    // var zhLocalization = xpath.select('//Localization[@local=\'ZH_CN\']', rootNode)[0];
                    // var zhName = xpath.select('string(//@localName)', zhLocalization);
                    // var zhAbstract = xpath.select('string(//Abstract)', zhLocalization);
                    //
                    // var enLocalization = xpath.select('//Localization[@local=\'EN_US\']', rootNode)[0];
                    // var enName = xpath.select('string(//@localName)', enLocalization);
                    // var enAbstract = xpath.select('string(//Abstract)', enLocalization);
                    xmlparse(cfgStr, {
                        explicitArray: false,
                        ignoreAttrs: false
                    }, function (err, json) {
                        if(err) {
                            console.log('Error in parse DataVisualizationMethod.xml : ' + err);
                            return cb(err);
                        }
                        newPackage.DVM = json;
                        VisualModel.save(newPackage,function (err, rst) {
                            if(err){
                                return cb(err);
                            }
                            return rst._doc._id;
                        })
                    });
                })
            })
        },

        // 后台内部使用，不对外暴露
        batchDeploy: function (fpath) {
            var dirList = FileOpera.getAllDir(fpath);
            for(let i=0;i<dirList.length;i++){
                if(dirList[i] == 'upload'){
                    continue;
                }
                var dirpath = path.join(__dirname,'../../visualization_service',dirList[i]);
                __deployPackage(dirpath,function (err, _id) {

                });
            }
        }

    }
})();